package xyz.prob.kun.biz.modules.system.service.impl;

import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import xyz.prob.kun.biz.modules.system.mapper.SysUserMapper;
import xyz.prob.kun.biz.modules.system.model.SysUser;
import xyz.prob.kun.biz.modules.system.params.LoginUserParam;
import xyz.prob.kun.biz.modules.system.params.SysUserRegisterParam;
import xyz.prob.kun.biz.modules.system.service.SysUserService;
import xyz.prob.kun.security.model.LoginUser;
import xyz.prob.kun.security.util.JwtUtil;


@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginUserParam loginUserParam) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserParam.getUserName(), loginUserParam.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return jwtUtil.createToken((LoginUser) authenticate.getPrincipal());
    }

    @Override
    public String register(SysUserRegisterParam registerParam) {
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(registerParam.getLoginName());
        sysUser.setName(registerParam.getLoginName());
        sysUser.setPassword(passwordEncoder.encode(registerParam.getPassword()));
        sysUserMapper.insert(sysUser);
        return null;
    }
}
